package org.budo.warehouse.service.bean;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.budo.support.spring.bean.factory.support.BeanBuilder;
import org.budo.support.spring.util.SpringUtil;
import org.budo.warehouse.service.entity.DataNode;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @author limingwei
 */
@Component
public class ServiceDynamicBeanProvider {
    @Resource
    private ApplicationContext applicationContext;

    public DataSource dataSource(DataNode dataNode) {
        String beanId = "DataSource-" + dataNode.getId() + "-" + dataNode.getUrl() + "-" + dataNode.getUsername();

        DataSource dataSource = (DataSource) SpringUtil.getBeanCached(this.applicationContext, beanId);
        if (null != dataSource) {
            return dataSource;
        }

        return (DataSource) new BeanBuilder() //
                .id(beanId) //
                .parent("abstractDruidDataSource") //
                .propertyValue("url", dataNode.getUrl()) //
                .propertyValue("username", dataNode.getUsername()) //
                .propertyValue("password", dataNode.getPassword()) //
                .registerTo(this.applicationContext) //
                .get();
    }
}